const jwt = require('jsonwebtoken')
const { SECRETKEY } = require('../config/dbkeys')
// 验证Token 中间件
const auth = async (req, res, next) => {
  // Bearer
  const auth = String(req.headers.authorization).split(' ').pop();
  try {
    // 解析token中存入的id
    const { id } = await jwt.verify(auth, SECRETKEY);
    req.body.id = id;
    next()
  } catch(ex) {
    if (ex.name === 'TokenExpiredError') {
      res.status(403).json({ status: -1, message: 'token过期' });
    } else if (ex.name === 'JsonWebTokenError') {
      res.status(403).json({ status: -1, message: '无效的token' });
    }
  }
}

module.exports = auth;